from flask import Blueprint, render_template, request, jsonify
from applications.common.utils.rights import authorize
from applications.common import curd
from applications.models import Wiki
from applications.common.utils.validate import xss_escape
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.curd import model_to_dicts, enable_status, disable_status
from applications.schemas import WikiOutSchema
from applications.common.utils import upload as upload_curd
from applications.extensions import db

admin_pest = Blueprint('adminPest', __name__, url_prefix='/')


# 病害wiki的视图

# 维基管理
@admin_pest.get('/pest_search')
@authorize("pest:search", log=True)
def main():
    return render_template('admin/pest/main.html')


# wiki增加页面
@admin_pest.get('/pest_search/add')
@authorize("pest:add", log=True)
def add():
    # roles = Role.query.all()   , roles=roles
    return render_template('admin/pest/pest_add.html')


# wiki编辑页面
@admin_pest.get('/pest_search/edit/<int:disease_num>')
@authorize("pest:edit", log=True)
def edit(disease_num):
    wiki_info = Wiki.query.get(disease_num)

    return render_template('admin/pest/pest_edit.html', wiki_info=wiki_info)


# wiki查看页面
@admin_pest.get('/pest_search/view/<int:disease_num>')
@authorize("pest:view", log=True)
def view(disease_num):
    wiki_info = Wiki.query.get(disease_num)

    return render_template('admin/pest/pest_view.html', wiki_info=wiki_info)


# wiki查询全部病害信息
@admin_pest.get('/pest_search/pest_info')
def data():
    # 获取请求参数
    disease_name = xss_escape(request.args.get('disease_name', type=str))
    disease_harm = xss_escape(request.args.get('disease_harm', type=str))
    disease_symptom = xss_escape(request.args.get('disease_symptom', type=str))
    # 查询参数构造
    mf = ModelFilter()
    if disease_name:
        mf.contains(field_name="disease_name", value=disease_name)
    if disease_harm:
        mf.contains(field_name="disease_harm", value=disease_harm)
    if disease_symptom:
        mf.exact(field_name="disease_symptom", value=disease_symptom)
    # orm查询
    # 使用分页获取data需要.items
    wiki_data = Wiki.query.filter(mf.get_filter(model=Wiki)).layui_paginate()
    count = wiki_data.total
    # 返回api
    return table_api(data=model_to_dicts(schema=WikiOutSchema, data=wiki_data.items), count=count)


# 上传病害图片
#   上传接口
@admin_pest.post('/pest_search/img')
def upload_api():
    if 'file' in request.files:
        photo = request.files['file']
        mime = request.files['file'].content_type

        file_url = upload_curd.upload_one(photo=photo, mime=mime)
        res = {
            "msg": "上传成功",
            "code": 0,
            "success": True,
            "data":
                {"src": file_url}
        }
        return jsonify(res)
    return fail_api()


# 添加wiki数据接口
@admin_pest.post('/pest_search/save')
@authorize("pest:add", log=True)
def save():
    req_json = request.json
    disease_name = xss_escape(req_json.get('disease_name'))
    disease_harm = xss_escape(req_json.get('disease_harm'))
    disease_symptom = xss_escape(req_json.get('disease_symptom'))
    disease_prevention = xss_escape(req_json.get('disease_prevention'))
    disease_img = xss_escape(req_json.get('disease_img'))

    disease_explain = xss_escape(req_json.get('disease_explain'))
    disease_access = 0

    if not disease_name or not disease_harm or not disease_symptom:
        return fail_api(msg="病名危害症状不得为空")

    if bool(Wiki.query.filter_by(disease_name=disease_name).count()):
        return fail_api(msg="病害数据已经存在")
    entry = Wiki(disease_name, disease_harm, disease_symptom, disease_prevention, disease_img, disease_explain,
                 disease_access)

    db.session.add(entry)
    db.session.commit()
    return success_api(msg="增加成功")


#  编辑
@admin_pest.put('/pest_search/update')
@authorize("pest:edit", log=True)
def update():
    req_json = request.json

    disease_num = xss_escape(req_json.get('disease_num'))
    disease_name = xss_escape(req_json.get('disease_name'))
    disease_harm = xss_escape(req_json.get('disease_harm'))
    disease_symptom = xss_escape(req_json.get('disease_symptom'))
    disease_prevention = xss_escape(req_json.get('disease_prevention'))
    disease_img = xss_escape(req_json.get('disease_img'))

    disease_explain = xss_escape(req_json.get('disease_explain'))
    disease_access = xss_escape(str(req_json.get('disease_access')))
    if not disease_name or not disease_harm or not disease_symptom:
        return fail_api(msg="病名危害症状不得为空")

    Wiki.query.filter_by(disease_num=disease_num).update({'disease_name': disease_name, 'disease_harm': disease_harm,
                                                          'disease_symptom': disease_symptom,
                                                          'disease_prevention': disease_prevention,
                                                          'disease_img': disease_img,
                                                          'disease_explain': disease_explain,
                                                          'disease_access': disease_access})
    w = Wiki.query.filter_by(disease_num=disease_num).first()

    db.session.commit()
    return success_api(msg="更新成功")


# 删除wiki
@admin_pest.delete('/pest_search/remove/<int:disease_num>')
@authorize("pest:remove", log=True)
def delete(disease_num):

    res = Wiki.query.filter_by(disease_num=disease_num).delete()

    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 批量删除
@admin_pest.delete('/pest_search/batchRemove')
@authorize("pest:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for disease_num in ids:
        res = Wiki.query.filter_by(disease_num=disease_num).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")
